<template>
  <div class="block-field-test">
    <el-card>
      <template #header>
        <h3>区块字段配置测试</h3>
      </template>
      
      <el-row :gutter="24">
        <!-- 区块选择 -->
        <el-col :span="8">
          <h4>选择测试区块</h4>
          <el-select v-model="selectedBlockId" placeholder="请选择区块" @change="loadBlockFields">
            <el-option
              v-for="block in blocks"
              :key="block.id"
              :label="block.name"
              :value="block.id"
            />
          </el-select>
          
          <div v-if="selectedBlock" style="margin-top: 16px;">
            <p><strong>区块名称：</strong>{{ selectedBlock.name }}</p>
            <p><strong>区块类型：</strong>{{ selectedBlock.type }}</p>
            <p><strong>区块ID：</strong>{{ selectedBlock.id }}</p>
          </div>
        </el-col>
        
        <!-- 字段列表 -->
        <el-col :span="16">
          <h4>当前字段配置</h4>
          <div v-if="loading" style="text-align: center; padding: 40px;">
            <el-icon class="is-loading"><Loading /></el-icon>
            <p>加载中...</p>
          </div>
          
          <div v-else-if="fields.length === 0" style="text-align: center; padding: 40px;">
            <el-empty description="暂无字段配置" />
          </div>
          
          <div v-else>
            <el-table :data="fields" border>
              <el-table-column prop="name" label="字段名称" width="120" />
              <el-table-column prop="label" label="字段标签" width="120" />
              <el-table-column prop="type" label="字段类型" width="100" />
              <el-table-column prop="required" label="必填" width="80">
                <template #default="{ row }">
                  <el-tag :type="row.required ? 'danger' : 'info'" size="small">
                    {{ row.required ? '是' : '否' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="orderNum" label="排序" width="80" />
              <el-table-column prop="description" label="描述" show-overflow-tooltip />
              <el-table-column label="操作" width="200">
                <template #default="{ row, $index }">
                  <el-button size="small" @click="editField(row, $index)">编辑</el-button>
                  <el-button size="small" type="danger" @click="deleteField($index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-col>
      </el-row>
      
      <el-divider />
      
      <!-- 操作按钮 -->
      <div style="text-align: center;">
        <el-button @click="addTestField" :disabled="!selectedBlockId">添加测试字段</el-button>
        <el-button type="primary" @click="refreshFields" :disabled="!selectedBlockId">刷新字段</el-button>
        <el-button type="success" @click="saveAllFields" :disabled="!selectedBlockId" :loading="saving">
          保存所有字段
        </el-button>
      </div>
      
      <el-divider />
      
      <!-- 调试信息 -->
      <el-collapse>
        <el-collapse-item title="调试信息" name="debug">
          <h5>API调用日志</h5>
          <div class="debug-logs">
            <div v-for="(log, index) in debugLogs" :key="index" class="debug-log">
              <span class="log-time">{{ log.time }}</span>
              <span class="log-type" :class="log.type">{{ log.type }}</span>
              <span class="log-message">{{ log.message }}</span>
              <pre v-if="log.data" class="log-data">{{ JSON.stringify(log.data, null, 2) }}</pre>
            </div>
          </div>
          
          <el-button size="small" @click="clearLogs">清空日志</el-button>
        </el-collapse-item>
      </el-collapse>
    </el-card>
    
    <!-- 字段编辑对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑字段" width="600px">
      <el-form :model="editingField" label-width="100px">
        <el-form-item label="字段名称">
          <el-input v-model="editingField.name" placeholder="请输入字段名称" />
        </el-form-item>
        <el-form-item label="字段标签">
          <el-input v-model="editingField.label" placeholder="请输入字段标签" />
        </el-form-item>
        <el-form-item label="字段类型">
          <el-select v-model="editingField.type">
            <el-option label="文本" value="text" />
            <el-option label="数字" value="number" />
            <el-option label="多行文本" value="textarea" />
            <el-option label="选择框" value="select" />
            <el-option label="图片" value="image" />
            <el-option label="文件" value="file" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否必填">
          <el-switch v-model="editingField.required" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="editingField.description" type="textarea" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEditingField">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Loading } from '@element-plus/icons-vue'
import { blockApi } from '@/api/block'

// 响应式数据
const selectedBlockId = ref<number | null>(null)
const blocks = ref<any[]>([])
const fields = ref<any[]>([])
const loading = ref(false)
const saving = ref(false)
const editDialogVisible = ref(false)
const editingField = ref<any>({})
const editingIndex = ref(-1)
const debugLogs = ref<any[]>([])

// 计算属性
const selectedBlock = computed(() => {
  return blocks.value.find(block => block.id === selectedBlockId.value)
})

// 方法
const addDebugLog = (type: string, message: string, data?: any) => {
  debugLogs.value.unshift({
    time: new Date().toLocaleTimeString(),
    type,
    message,
    data
  })
  
  // 只保留最近50条日志
  if (debugLogs.value.length > 50) {
    debugLogs.value = debugLogs.value.slice(0, 50)
  }
}

const loadBlocks = async () => {
  try {
    addDebugLog('INFO', '开始加载区块列表')
    const response = await blockApi.getList({ current: 1, size: 100 })
    addDebugLog('SUCCESS', '区块列表加载成功', response)
    
    if (response.code === 0) {
      blocks.value = response.data?.records || response.data?.list || []
    }
  } catch (error) {
    addDebugLog('ERROR', '加载区块列表失败', error)
    ElMessage.error('加载区块列表失败')
  }
}

const loadBlockFields = async () => {
  if (!selectedBlockId.value) return
  
  loading.value = true
  try {
    addDebugLog('INFO', `开始加载区块字段: ${selectedBlockId.value}`)
    const response = await blockApi.getFields(selectedBlockId.value)
    addDebugLog('SUCCESS', '字段加载成功', response)
    
    if (response.code === 0) {
      fields.value = (response.data || []).map((field: any) => ({
        ...field,
        options: field.options ? JSON.parse(field.options) : []
      }))
    }
  } catch (error) {
    addDebugLog('ERROR', '加载字段失败', error)
    ElMessage.error('加载字段失败')
  } finally {
    loading.value = false
  }
}

const addTestField = () => {
  const newField = {
    id: `test_${Date.now()}`,
    name: `test_field_${Date.now()}`,
    label: `测试字段${fields.value.length + 1}`,
    type: 'text',
    description: '这是一个测试字段',
    required: false,
    orderNum: fields.value.length + 1,
    status: 1
  }
  
  fields.value.push(newField)
  addDebugLog('INFO', '添加测试字段', newField)
}

const editField = (field: any, index: number) => {
  editingField.value = { ...field }
  editingIndex.value = index
  editDialogVisible.value = true
}

const saveEditingField = () => {
  if (editingIndex.value >= 0) {
    fields.value[editingIndex.value] = { ...editingField.value }
    addDebugLog('INFO', '字段编辑完成', editingField.value)
  }
  editDialogVisible.value = false
}

const deleteField = async (index: number) => {
  const field = fields.value[index]
  try {
    await ElMessageBox.confirm(`确定要删除字段"${field.label}"吗？`, '确认删除', {
      type: 'warning'
    })
    
    fields.value.splice(index, 1)
    addDebugLog('INFO', '字段删除成功', field)
    ElMessage.success('字段删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      addDebugLog('ERROR', '删除字段失败', error)
    }
  }
}

const saveAllFields = async () => {
  if (!selectedBlockId.value) return
  
  saving.value = true
  try {
    addDebugLog('INFO', `开始保存字段到区块: ${selectedBlockId.value}`)
    
    const fieldsData = fields.value.map(field => ({
      ...field,
      options: field.options && field.options.length > 0 ? JSON.stringify(field.options) : null
    }))
    
    addDebugLog('INFO', '准备保存的字段数据', fieldsData)
    
    const response = await blockApi.saveFields(selectedBlockId.value, fieldsData)
    addDebugLog('SUCCESS', '字段保存成功', response)
    
    if (response.code === 0) {
      ElMessage.success('字段保存成功')
      await loadBlockFields() // 重新加载
    } else {
      throw new Error(response.msg || '保存失败')
    }
  } catch (error) {
    addDebugLog('ERROR', '保存字段失败', error)
    ElMessage.error('保存字段失败: ' + (error.message || '未知错误'))
  } finally {
    saving.value = false
  }
}

const refreshFields = () => {
  loadBlockFields()
}

const clearLogs = () => {
  debugLogs.value = []
}

onMounted(() => {
  loadBlocks()
})
</script>

<style scoped lang="scss">
.block-field-test {
  padding: 20px;
  
  h4 {
    margin: 0 0 16px 0;
    color: #303133;
    font-size: 16px;
    font-weight: 600;
  }
  
  h5 {
    margin: 8px 0 4px 0;
    color: #606266;
    font-size: 14px;
    font-weight: 600;
  }
  
  .debug-logs {
    max-height: 400px;
    overflow-y: auto;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    padding: 8px;
    background: #fafafa;
    
    .debug-log {
      margin-bottom: 8px;
      font-size: 12px;
      
      .log-time {
        color: #909399;
        margin-right: 8px;
      }
      
      .log-type {
        padding: 2px 6px;
        border-radius: 3px;
        margin-right: 8px;
        font-weight: 600;
        
        &.INFO {
          background: #e1f3d8;
          color: #67c23a;
        }
        
        &.SUCCESS {
          background: #e1f3d8;
          color: #67c23a;
        }
        
        &.ERROR {
          background: #fde2e2;
          color: #f56c6c;
        }
      }
      
      .log-message {
        color: #303133;
      }
      
      .log-data {
        margin: 4px 0 0 80px;
        padding: 8px;
        background: white;
        border-radius: 3px;
        font-size: 11px;
        max-height: 200px;
        overflow-y: auto;
      }
    }
  }
}
</style>
